<?php
namespace Admin\Controller;
use Think\Controller;

class RefundController extends \Org\Util\AdminController {



    /**
     * 权限验证标志位,默认false
     * false:所有action都需要权限验证;
     * true:所有action都不需要权限验证;
     * array:array中的action不需要权限验证，其余需要。
     */
    protected $notAuthority = false;


    /**
     * 创建之后做的事情
     */
    public function interfaceAfterCreate($id) {
    }

    /**
     * 删除之前做的事情
     */
    public function interfaceBeforeDelete($id) {
    }

    /**
     * 更新之前做的事情
     */
    public function interfaceBeforeUpdate($id) {
    }

    /**
     * 父类中已经有典型的CRUD操作并预留入口
     * 如有较大改动则覆盖一下
     */
    public function create() {
        parent::create();
    }

    public function delete() {
        parent::delete();
    }

    public function update($id) {
        $refund = D('Refund')->find($id);
        if (($refund['state'] == '待处理') && ($_POST['state'] == '同意')) {
            if ($refund['order_type'] == 'FundingOrder') {
                $order = D('FundingOrder')->where(['id'=>$refund['order_id']])->find();
                $funding = D('Funding')->find($order['funding_id']);
                $already_num = $funding['already_num'] -1;
                //减少众筹人数
                D('Funding')->where(['id'=>$funding['id']])->data(['already_num'=> $already_num])->save();
                //修改订单状态
                D('FundingOrder')->where(['id'=>$refund['order_id']])->data(['state'=>'已退款'])->save();
                //增加资金明细记录
                unset($data);
                $data['user_id'] = $refund['user_id'];
                $data['pay_type'] = '-';
                $data['amount'] = ($order['insurance_price']+$funding['funding_price']);
                $data['remark'] = '退款';
                $data['order_type'] = $refund['order_type'];
                $data['order_id'] = $refund['order_id'];
                D('Finance')->create($data);
                D('Finance')->add();
                //给用户增加余额
                $user = D('User')->find($order['user_id']);
                $newBalance = ($user['balance'] + $order['insurance_price']+$funding['funding_price']);
                D('User')->where(['id'=>$order['user_id']])->data(['balance'=>$newBalance])->save();
            }
        } elseif (($refund['state'] == '待处理') && ($_POST['state'] == '拒绝')) {
                D('FundingOrder')->where(['id'=>$refund['order_id']])->data(['state'=>'已拒绝退款'])->save();

        }
        parent::update($id);
    }

    public function list() {
        parent::list();
    }

    public function detail($id = 0) {
        parent::detail($id);
    }

    public function import() {
        parent::import();
    }

    public function export() {
        parent::export();
    }
}
